/*
使用方法：

**** 引入
<link href="../css/uploader.css" rel="stylesheet">
<script src="../js/uploader.js"></script>

**** HTML
<div class="file-uploader" id="id-1" 
    data-icon="/img/innjia.png" 
    data-title="身份证人像面" 
    data-drop="true"
    data-readonly="true">
</div>
<div class="file-uploader" id="id-2" 
    data-icon="/img/innjia.png" 
    data-title="身份证国徽面">
</div>

data-icon      默认提示上传图片
data-title     标题
data-drop      是否开启拖放上传
data-readonly  是否只读查看

**** JS
var id1 = new Uploader({ at: $('#id-1'), value: "..." })
var id2 = new Uploader({ at: $('#id-2') })

*** 属性
at: 组件dom位置
value: 初始值，比如编辑的图片路径

*** 事件
success: 上传成功
error: 上传失败
complete: 上传完成

**** 方法
id1.val()      // 文件上传后在服务器端的存放路径
id1.val("...") // 赋值，并显示该图片
id1.reset()    // 重置整个控件
id1.bad()      // 标题背景红色，警告提示
id1.good()     // 标题背景绿色，成功提示
id1.lock()     // 打开只读
id1.unlock()   // 取消只读
*/

var Uploader = function (opt) {

    var fileHost = 'http://dev-xa.yingjiashenghuo.com/admin'; //'http://localhost:8080/admin';
    var innjiaLogo = '/statics/images/innjia-logo.png';

    this._vm = {};
    this._reader = new FileReader();

    this._el = function (opt) {
        this._vm.outter = opt;
        var icon = opt.data('icon');
        if (!icon) { icon = innjiaLogo; }
        if (icon.indexOf('http://') < 0) { icon = fileHost + icon; }
        var _this = this;
        this._vm.icon = $('<img>').addClass('icon').css({
                    top: '-9999px',
                    left: '-9999px'
                }).on('load', function() {
                    _this._resizeImg();
                }).attr('src', icon);

        this._vm.title = $('<div>').addClass('title').text(opt.data('title'));
        this._vm.hiddenfile = $('<input>').attr({
                    type: 'file',
                    accept: "image/jpeg, image/x-png"
                });
        this._vm.remove = $('<div>').addClass('icon-remove');
        this._vm.wrap = $('<div>').addClass('inner').append([
                    this._vm.icon, 
                    this._vm.title, 
                    this._vm.hiddenfile,
                    this._vm.remove
                ]);
        if (opt.data('drop')) {
            this._vm.outter.addClass('dragtrigger');
        }
        return this._vm.wrap;
    };

    this._render = function () {
        this.opt.at.html('').append(this._el(this.opt.at));
        this._isloaded = false;
        if (this.opt.at.data('readonly')) {
            this.lock();
        } else {
            this._alive();
        }
    };

    this._resizeImg = function (width, height) {
        var img = this._vm.icon,
            wrap = this.opt.at,
            title = this._vm.title,
            top = (wrap.height() - title.height() - (img.height() || height)) / 2,
            left = (wrap.width() - (img.width() || width)) / 2;
        img.css({
            top: top + 'px',
            left: left + 'px'
        });
    };

    this._readFile = function (evt) {
        var files = evt.target.files;

        if (files && files.length > 0) {
            var file = files[0];
            this._reader.readAsDataURL(file);
            var _this = this;
            this._reader.onloadend = function (result) {
        
                _this._vm.icon.css({
                    top: '-9999px',
                    left: '-9999px'
                }).attr('src', _this._reader.result);
                _this._saveFile()
            }
        }
    };

    this._saveFile = function () {
        // var $formData = new FormData();
        // $formData.append("img", this._reader.result);

        // this._reader.result is base64 string

        // this.isNew = !this._value;
        // this._value = "1234";
        // if ("function" == typeof this.opt.success) { this.opt.success(this); }
        var mimetype = this._reader.result.split(',').shift(), type;
        switch(mimetype) {
            case "data:image/jpeg;base64":
                type = "jpg";
                break;
            case "data:image/png;base64":
                type = "png";
                break;
            case "data:image/gif;base64":
                type = "gif";
                break;
            default:
                type = "jpg";
        }
        var base64str = this._reader.result.replace(mimetype+',', '');
        var _this = this
        $.ajax({
            url: "/admin/file/image/house/info",
            type: 'POST',
            data: JSON.stringify({ path: base64str, type: type }), // 这个path其实是base64Str
            contentType: 'application/json; charset=utf-8',
            async: true,
            cache: false,
            processData: false,
            success: function (result) {
                console.log(result)
                if ("0" == result.code) {
                    _this.isNew = !_this._value;
                    _this._value = result.imageUrl;
                    _this.opt.at.attr("imgUrl", result.imageUrl);
                    // _this.opt.at.attr("id", 'reset-' + uuid.n8());
                    _this._vm.title.addClass('is-good');
                    _this._isloaded = true;
                    _this._vm.remove.show();
                    if ("function" === typeof _this.opt.success) {
                        _this.opt.success(_this)
                    }
                } else {
                    if ("function" === typeof _this.opt.error) {
                        _this.opt.error(_this)
                    }
                }
            },
            error: function () {
                _this._vm.title.addClass('is-bad');
                console.log('error');
                if ("function" === typeof _this.opt.error) {
                    _this.opt.error(_this)
                }
            },
            complete: function() {
                if ("function" === typeof _this.opt.complete) {
                    _this.opt.complete(_this)
                }
            }
        });

    }

    this._alive = function () {
        var _this = this;
        this.opt.at.off('click').on('click', function (e) {
            if (_this._islocked) return false;
            var trigger = _this._vm.hiddenfile[0];
            trigger.addEventListener('change', _this._readFile, false);
            trigger.click();
        })
        this._vm.remove.off('click').on('click', function (e) {
            if (_this._islocked) return false;
            e.preventDefault();
            _this.reset('deleted');

            //wangyuan: 判断上传控件个数, 大于1时移除当前被删除的控件
            if(_this.opt.parent && _this.opt.parent.children('.file-uploader')
               && _this.opt.parent.children('.file-uploader').length > 1){
                console.log(_this.opt.parent.children('.file-uploader').length);
                _this.opt.at.remove();
            }else{
                //重置ID, imgUrl
                _this.opt.at.attr("id", 'reset-' + uuid.n8());
                _this.opt.at.attr("imgUrl", "");
            }

            return false;
        })

        if (this._vm.outter.hasClass('dragtrigger')) { // drag drop
            var ignoreDrag = function(e) {
                var event = typeof e.originalEvent != 'undefined' ? e.originalEvent : e;
                if (event.stopPropagation) {
                    event.stopPropagation();
                }
                if (event.preventDefault) {
                    event.preventDefault();
                }
            };
            this._vm.outter
              .off("dragover").on("dragover", function () {
                if (_this._islocked) return false;
                _this._vm.outter.addClass('dragover');
                return false;
            })
              .off("dragleave").on("dragleave", function () {
                if (_this._islocked) return false;
                _this._vm.outter.removeClass('dragover');
                return false;
            })
            .off('drop').on("drop", function (e) {
                if (_this._islocked) return false;
                _this._vm.outter.removeClass('dragover');
                e = (e&&e.originalEvent?e.originalEvent:window.event) || e;
                ignoreDrag(e);

                var files = (e.files || e.dataTransfer.files);
                var file = files[0];                    

                if (file.type != 'image/jpeg' && file.type != 'image/png') {
                    // return false;
                }
                if (file.size > 2048000) {
                    alert('太大啦！');
                    return false;
                }
                console.log(file);

                _this._reader.readAsDataURL(file);
                _this._reader.onloadend = function (result) {
            
                    _this._vm.icon.css({
                        top: '-9999px',
                        left: '-9999px'
                    }).attr('src', _this._reader.result);

                    _this._saveFile()
                }

                return false;
            });            

        }
    };

    this.lock = function () {
        this._islocked = true;
        this._vm.outter.css({cursor: 'auto'});
        this._vm.remove.hide();
    }

    this.unlock = function () {
        this._islocked = false;
        this._vm.outter.css({cursor: 'pointer'});
        if (this._isloaded) {
            this._vm.remove.show();
        }
    }

    this.reset = function (event) {
        this.opt.at.html("");
        this._value = event || "";
        this._render();
    }

    this.bad = function () {
        this._vm.title.removeClass('is-good').addClass('is-bad');
    }

    this.good = function () {
        this._vm.title.removeClass('is-bad').addClass('is-good');
    }

    this.val = function (value) {
        if (!value) {
            return this._value;
        }

        this._value = value;
        this._vm.icon.css({
            top: '-9999px',
            left: '-9999px'
        }).attr('src', fileHost + this._value);
        this._isloaded = true;

        if (!this.opt.at.data('readonly')) {
            this._vm.remove.show();
        }
        this.good();
    }

    this._init = function (opt) {
        this.opt = opt || {};
        this._value = "";
        this._render();
        if (opt.value) {
            this.val(opt.value);
        }
    };
    this._init(opt);
}